package com.wct.demo.gui;

import com.wct.demo.BankApp;
import com.wct.demo.BankTask;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author WEI (Email:changtan20000@163.com)
 * @description 取号机界面
 * @date: 2019/12/23 12:32
 */
@Slf4j
public class UserGUI {
    private JButton button1;
    private JButton button2;
    private JButton button3;
    private JButton button4;
    private JButton button5;

    private JLabel topLabel;
    private JTextPane timeLabel;

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private static final String[] TYPES = {"存款", "取款", "开户", "挂失", "其他"};

    private static AtomicLong atomicLong = new AtomicLong(0);

    public void createAndShowGUI() {

        // 边距
        Border border = new EmptyBorder(10, 10, 10, 10);

        JPanel topPanel = new JPanel();
        topPanel.setBorder(border);
        topPanel.setLayout(new GridLayout(1, 2, 10, 10));
        topLabel = new JLabel("Hello Welcome!");
        // 设置字体
        topLabel.setFont(new Font(null, Font.PLAIN, 20));
        timeLabel = new JTextPane();

        timeLabel.setFont(new Font(null, Font.PLAIN, 20));
        topPanel.add(topLabel);
        topPanel.add(timeLabel);


        GridLayout gridLayout = new GridLayout(3, 2, 10, 10);
        gridLayout.setHgap(20);
        gridLayout.setVgap(20);

        JPanel panel1 = new JPanel(gridLayout);
        panel1.setBorder(border);

        button1 = new JButton(TYPES[0]);
        button1.addActionListener(e -> {
            // 1.生成任务 2. 把任务添加到阻塞队列中
            addTask(button1.getText());
        });
        panel1.add(button1);

        button2 = new JButton(TYPES[1]);
        button2.addActionListener(e -> {
            // 1.生成任务 2. 把任务添加到阻塞队列中
            addTask(button2.getText());
        });
        panel1.add(button2);

        button3 = new JButton(TYPES[2]);
        button3.addActionListener(e -> {
            // 1.生成任务 2. 把任务添加到阻塞队列中
            addTask(button3.getText());
        });
        panel1.add(button3);

        button4 = new JButton(TYPES[3]);
        button4.addActionListener(e -> {
            // 1.生成任务 2. 把任务添加到阻塞队列中
            addTask(button4.getText());
        });
        panel1.add(button4);

        button5 = new JButton(TYPES[4]);
        button5.addActionListener(e -> {
            // 1.生成任务 2. 把任务添加到阻塞队列中
            addTask(button5.getText());
        });
        panel1.add(button5);


        JPanel mainPanel = new JPanel(new GridLayout(2, 1, 10, 10));
        mainPanel.add(topPanel);
        mainPanel.add(panel1);
        //Create and set up the window.
        JFrame frame = new JFrame("UserGUI");
        // 设置当窗体关闭的操作时，程序结束
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setContentPane(mainPanel);
        // setPreferredSize需要在使用布局管理器的时候使用
        frame.setPreferredSize(new Dimension(600, 400));

        // 设置窗体可显示
        frame.pack();
        frame.setVisible(true);
        // 设置窗体居中显示
        frame.setLocationRelativeTo(null);

        // 时间显示
        Timer timer = new Timer(1000, e -> {
            // 获取到当前时间并按格式显示

            if (BankApp.getIsOpen()) {
                timeLabel.setText("正在营业\nTime: " + LocalDateTime.now().format(DATE_TIME_FORMATTER));
            } else {
                timeLabel.setText("停止营业\nTime: " + LocalDateTime.now().format(DATE_TIME_FORMATTER));
            }
        });
        timer.start();

    }

    /**
     * @param size 当前有多少人正在排队
     */
    public void updateWaitText(Integer size) {
        SwingWorker<Integer, Void> worker = new SwingWorker<Integer, Void>() {
            @Override
            protected Integer doInBackground() {
                return size;
            }

            @Override
            protected void done() {
                try {
                    topLabel.setText("当前有 " + get() + " 人在等待");
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            }
        };
        worker.execute();
    }

    private void addTask(String taskType) {
        // 银行是否正在营业

        if (BankApp.getIsOpen()) {
            /*
             * 处理剩余排队业务所需的时间小于银行营业时间
             *  4 * 15 < 60
             * */
            if (BankApp.getQueueSize() * (BankApp.getTaskProcessTime() / 2) < BankApp.getBankBusinessTime()) {
                // 新建业务
                BankTask task = new BankTask();
                // 设置业务id
                task.setId(atomicLong.incrementAndGet());
                // 设置业务类型
                task.setType(taskType);
                // 设置排队开始时间
                task.setWaitStartTime(LocalDateTime.now());
                // 弹出对话框，显示排队号码等信息
                String msg = "号码：" + task.getId() + "\n业务类型：" + task.getType() + "\n排队时间：" + task.getWaitStartTime().format(DATE_TIME_FORMATTER) + "\n前面有 " + BankApp.getQueueSize() + " 人在等待";
                JOptionPane.showMessageDialog(null, msg, "取号成功", JOptionPane.INFORMATION_MESSAGE);
                // 添加到阻塞队列中
                BankApp.addQueue(task);
                // 更新topLabel
                updateWaitText(BankApp.getQueueSize());
            } else {
                JOptionPane.showMessageDialog(null, "当前等待人数过多", "取号失败", JOptionPane.INFORMATION_MESSAGE);
            }
        } else {
            // 弹出对话框
            String msg = "银行未开始营业";
            JOptionPane.showMessageDialog(null, msg, "取号失败", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    public static void main(String[] args) throws Exception {
        UserGUI userGUI = new UserGUI();
        SwingUtilities.invokeLater(userGUI::createAndShowGUI);

        Thread.sleep(2000);
    }


}
